﻿using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.DrawingCore;
using System.DrawingCore.Imaging;
using System.Net.Http;
using System.Collections.Generic;
using chihuopig.Model;
using System.Threading.Tasks;

namespace chihuopig.Tool
{
    public static class UtilityHelper
    {
        public static string GetMd5(string value, string salt)
        {
            StringBuilder sb = new StringBuilder();
            MD5 md5 = MD5.Create();
            byte[] t = Encoding.UTF8.GetBytes(value + salt);
            byte[] compbyte = md5.ComputeHash(t);
            foreach (var item in compbyte)
            {
                sb.Append(item.ToString("x"));
            }
            return sb.ToString();
        }

        public static void SetCookie(string key, string value, DateTime dt)
        {

            IHttpContextAccessor Accessor = new HttpContextAccessor();
            CookieOptions cookie = new CookieOptions();
            cookie.Expires = dt;
            /*cookie.Path = "/";
            cookie.Domain=Accessor.HttpContext.Request.Host.Value;*/
            Accessor.HttpContext.Response.Cookies.Append(key, value, cookie);

        }

        public static void DeleteCookie(string key)
        {
            IHttpContextAccessor Accessor = new HttpContextAccessor();
            CookieOptions o = new CookieOptions();
            o.Expires = DateTime.Now.AddDays(-1);
            Accessor.HttpContext.Response.Cookies.Delete(key, o);
        }

        public static string GetCookieValue(string Cookie, string Key)
        {
            IHttpContextAccessor Context = new HttpContextAccessor();
            string Collection = Context.HttpContext.Request.Cookies[Cookie];
            return Collection == null ? "" : UtilityHelper.DESDecrypt(Collection, CookieKeysCollection.Buffalo_Admin_Key, CookieKeysCollection.Buffalo_Admin_IV);
        }

        public static string MemberGetCookieValue(string Key)
        {
            IHttpContextAccessor Context = new HttpContextAccessor();
            return Context.HttpContext.Request.Cookies[Key]??"";
          
        }

        public static MemoryStream GetMemoryCode(out string str)
        {
            StringBuilder chkCode = new StringBuilder();
            string[] num = { "0", "1", "A", "C", "图", "关", "2", "以", "并", "3", "4", "5", "6", "7", "8", "9", "张", "蝉", "布" };
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            int codeW = 80;
            int codeH = 30;
            int fontSize = 16;
            for (int i = 0; i < 4; i++)
            {

                chkCode.Append(num[new Random().Next(0, 15)]);
            }
            str = chkCode.ToString();
            Random rnd = new Random();
            //颜色列表，用于验证码、噪线、噪点 
            System.Drawing.Color[] color = { System.Drawing.Color.Black, System.Drawing.Color.Red, System.Drawing.Color.Blue, System.Drawing.Color.Green, System.Drawing.Color.Orange, System.Drawing.Color.Brown, System.Drawing.Color.Brown, System.Drawing.Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman" };
            //验证码的字符集，去掉了一些容易混淆的字符 

            //写入Session、验证码加密
            //WebHelper.WriteSession("session_verifycode", Md5Helper.MD5(chkCode.ToLower(), 16));
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(System.DrawingCore.Color.White);
            //画噪线 
            for (int i = 0; i < 1; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                System.Drawing.Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(System.DrawingCore.Color.Blue), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                System.Drawing.Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(System.DrawingCore.Color.Black), (float)i * 18, (float)0);
            }

            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return ms;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }

        }

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <returns>密文</returns>
        public static string DESEncrypt(string plainStr, string Key, string Iv)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(Iv);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return encrypt;
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public static string DESDecrypt(string encryptStr, string Key, string IV)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return decrypt;
        }


        public static string SaveBase64Img(string imgbase64Data)
        {
            string imgpath = "";
            if (!string.IsNullOrEmpty(imgbase64Data))
            {
                try
                {


                    //imgbase64Data.Substring(0, imgbase64Data.IndexOf(','));
                    string strnewstr = imgbase64Data.Replace(imgbase64Data.Substring(0, imgbase64Data.IndexOf(",") + 1), "");
                    //strnewstr = strnewstr.Replace("data:image/png;base64,", "");
                    //strnewstr = strnewstr.Replace("data:image/gif;base64,", "");
                    MemoryStream stream = new MemoryStream(Convert.FromBase64String(strnewstr));
                    Bitmap img = new Bitmap(stream);
                    string strimgtitle = DateTime.Now.ToString("yyyyMMddHHmmss");

                    //Task
                    string imgpathstr = System.Environment.CurrentDirectory + "\\wwwroot\\upload\\";
                    //如果音频目录不存在就创建/upload/201607041642111875/0001.jpg

                    string strmapath = imgpathstr + strimgtitle + ".jpg";
                    img.Save(strmapath);
                    imgpath = "/upload/" + strimgtitle + ".jpg";
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
            return imgpath;
        }

        public static string SaveShtml(string Temppath, string Content,string SavePath,string FielName)
        {
            try
            { 
                StringBuilder text = new StringBuilder();
                using (StreamReader read = new StreamReader(Temppath))
                using (StreamWriter writer = new StreamWriter(SavePath))
                {
                    while (read.Peek() > 0)
                    {
                        text.Append((char)read.Read());
                        //ts.SyncRoot
                    }
                    string html= text.ToString().Replace("@@content", Content);
                    writer.Write(html);
                }
            }
            catch(Exception ex)
            {
                return "";
            }
            return FielName;
        }

        public static string SaveShtml(string path, string FielName,string Content)
        {
            try
            {
                StringBuilder text = new StringBuilder();
             
                using (StreamWriter writer = new StreamWriter(path))
                {
                    
                    writer.Write(Content);
                }
            }
            catch (Exception ex)
            {
                return "";
            }
            return FielName;
        }

        public static async Task<string>  FindHtmlContent(string Path)
        {
            StringBuilder text = new StringBuilder();
            try
            {
               
                using (Stream read =File.OpenRead(Path))
                {
                    byte[] chars = new byte[read.Length];
                    int reasd = 0;
                    while ((reasd=await read.ReadAsync(chars,0, chars.Length))>0)
                    {
                      
                      text.Append(Encoding.UTF8.GetString(chars));
                        
                    
                        //ts.SyncRoot
                    }
                
                }

            }
            catch (Exception ex)
            {
                return "";
            }
            return text.ToString();
        }
    }
}
